const Base = require('./base.js');
const jwt = require('jsonwebtoken');
// 用户登录状态下所有控制器都应该要继承此
module.exports = class extends Base {
    /**
     * 判断用户是否登录，所有需要登录的页面继承此类
     */
    async __before() {
        var _this = this;
        const flag = await super.__before();
        // 如果父级想阻止后续继承执行会返回 false，这里判断为 false 的话不再继续执行了。
        if (flag === false) return false;
        // 其他逻辑代码
        if (!_this.header.hasOwnProperty('openid') || !_this.header['openid']) {
            return _this.fail(1, '当前微信账户尚未完成绑定');
        }
        try {
            _this.user = await think.model('wx_binduser','mh_user').where({"OpenId":this.header['openid']}).find();
        } catch (err) {
            return _this.fail(1, '用户信息异常,请联系管理员');
        }
    }

    /*
    * 获取用户信息
    */
    async getUserInfoAction(){
        let bindinfo = this.user;
        if(think.isEmpty(bindinfo))
        {
            return this.fail(1,'用户数据异常');
        }
        let user = await think.model('user','mh_user').where({'Id':bindinfo.userid}).field('Id as id,name as username,nameOfEnglish,brithday,mobile,sType').find();
        let newuser={
            "openid":bindinfo.OpenId,
            "id":bindinfo.userid,
            "username":bindinfo.UseName,
            "nameOfEnglish":user.nameOfEnglish,
            "brithday":user.brithday,
            "mobile":user.mobile,
            "sType":bindinfo.sType,
        }
        return this.success(newuser,'ok');
    }


    /*
    * 获取运费信息
    * area 区域
    */
    async getPriceListAction(){
        let sType = this.user.sType;
        let area = this.post('area');
        if(think.isEmpty(area))
        {
            return this.fail(1,'请选择区域');
        }
        if(sType==1)
        {
            let order ={
                "area":'asc',
                'place':'asc'
            };
            let list = await think.model('truck_pricelist','mh_truck').where({"isdelete":0,"area":area}).field('Id,area,place,sk_freight,sk_output,yict_freight,yict_output').group('place').order(order).select();
            return this.success(list,'ok');
        }else if(sType==2)
        {
            let order ={
                "area":'asc',
                'place':'asc'
            };
            let list2 = await think.model('truck_pricelist','mh_truck').where({"isdelete":0,"area":area}).field('Id,area,place,sk_freight,yict_freight').group('place').order(order).select();
            return this.success(list2,'ok');
        }else if(sType==3)
        {
            let order ={
                "area":'asc',
                'place':'asc'
            };
            let list3 = await think.model('truck_pricelist','mh_truck').where({"isdelete":0,"area":area}).field('Id,area,place,sk_output,yict_output').group('place').order(order).select();
            return this.success(list3,'ok');
        }
        return this.fail(1,'暂无数据');
    }
    /**
    * 获取运输信息列表
    */
    async getTransListAction(){
        let querydate = this.post('date');
        let date=querydate.split('-');
        let newdatestart = new Date(parseInt(date[0]),parseInt(date[1])-1,parseInt(date[2])).setHours(0,0,0,0)
        let newdateend = new Date(parseInt(date[0]),parseInt(date[1])-1,parseInt(date[2])).setHours(23,59,59,59);
        newdatestart=global.date(parseInt(newdatestart)/1000,1);
        newdateend=global.date(parseInt(newdateend)/1000,1);

        let sql=' select a.id as t_soId, ' +
                ' DATE_FORMAT(b.dateofPlan, \'%m-%d %H:%i\') as dateofPlan,  ' +
                ' a.so ,                 ' +
                ' (case a.customertype when 0 then f.code when 1 then h.code end) as customercode,   ' +
                ' (case when length(b.anothername) > 3 then b.anothername else a.so end) as blname ,' +
                ' a.shipper ,            ' +
                ' b.remarks as ctnrRemarks,' +
                ' a.customerId ,         ' +
                ' a.employeeid,          ' +
                ' f.id as t_customerId,  ' +
                ' b.id as t_ctnrId,      ' +
                ' b.placeofget,          ' +
                ' b.placeofloadarea,     ' +
                ' b.placeofload,         ' +
                ' b.placeofback ,        ' +
                ' b.size,      ' +
                ' b.isDoubleCtnr,        ' +
                ' b.needToWeight ,       ' +
                ' n.isAppiont,       ' +
                ' b.multiLoading ,       ' +
                ' g.code as truckcompanycode,' +
                ' b.truck ,              ' +
                ' b.containerNo,         ' +
                ' b.seal,         ' +
                ' b.weight,' +
                ' b.Trucker as name,                ' +
                ' b.TruckMobile as mobile ,             ' +
                ' a.customerType ,'        +
                ' a.billType, '            +
                ' a.isLoading ,'           +
                ' cs.fcolor ,'           +
                ' m.eir_code as eir_shippercode,            ' +
                ' cs.stype as state,               ' +
                ' b.isUse as ctnrIsUse,  ' +
                ' a.isUse as soIsUse     ' +
                ' from mh_truck.truck_so a        ' +
                ' left join mh_truck.truck_ctnr b on b.blid = a.id        ' +
                ' left join mh_supplier.sp_truckcompany g on g.id = b.truckCompanyId     ' +
                ' left join mh_supplier.sp_customer f on f.id = a.customerid  ' +
                ' left join mh_supplier.sp_truckcompany h on h.id= a.customerid ' +
                ' left join mh_supplier.sp_shipper m on m.code = a.shipper ' +
                ' left join mh_truck.ctnr_state n on n.ctnrid = b.id  ' +
                ' left join mh_form.list_ctnrstate cs on cs.Id = b.Idx_ctnrstate  ' +
                ' where ( b.dateofPlan >= \''+newdatestart+'\' and b.dateofPlan <= \''+newdateend+'\')';
        let sType = this.user.sType;
        if(sType==1)
        {

        }else if(sType==2)
        {
            sql+=' and a.customerType = 0 and a.customerid = '+this.user.SupplierId;
        }else if(sType==3)
        {
            sql+=' and b.Trucker = \''+this.user.CName+'\'';
        }
        sql+=' and b.isUse = 0 and a.isuse = 0 order by b.dateofPlan desc';

        let list = await think.model('truck_so','mh_truck').query(sql);

        if(think.isEmpty(list))
        {
            return this.fail(1,'暂无数据');
        }else{
            return this.success(list,'ok');
        }
    }

    /**
    *获取供应商订单详情列表
    */
    async getconlistAction(){
        let t_ctnrId = this.get('t_ctnrId');
        if(think.isEmpty(t_ctnrId))
        {
            return this.fail(1,'参数异常,无法获取详情');
        }
        let list = await think.model('truck_ctnr','mh_truck').where({'blid':t_ctnrId}).field('containerNo,size,weight as scount').select();
        if(think.isEmpty(list))
        {
            return this.fail(1,'暂无数据');
        }else{
            return this.success(list,'ok');
        }
    }

    /**
    * 获取托运详情
    */
    async getTransDetailAction(){
        let t_ctnrId = this.get('t_ctnrId');
        if(think.isEmpty(t_ctnrId))
        {
            return this.fail(1,'参数异常,无法获取详情');
        }
        let sql=' select a.id as t_soId, ' +
                ' DATE_FORMAT(b.dateofPlan, \'%Y-%m-%d %H:%i\') as dateofPlan,  ' +
                ' a.so ,                 ' +
                ' (case when length(b.anothername) > 3 then b.anothername else a.so end) as blname ,' +
                ' a.shipper ,            ' +
                ' b.remarks as ctnrRemarks,' +
                ' a.customerId ,         ' +
                ' a.employeeid,          ' +
                ' b.id as t_ctnrId,      ' +
                ' b.placeofget,          ' +
                ' b.placeofloadarea,     ' +
                ' b.placeofload,         ' +
                ' b.placeofback ,        ' +
                ' b.size,      ' +
                ' b.isDoubleCtnr,        ' +
                ' b.needToWeight ,       ' +
                ' b.multiLoading ,       ' +
                ' b.truck ,              ' +
                ' b.AllowViewGps ,       ' +
                ' b.containerNo,         ' +
                ' b.ctnrWeight, '+
                ' b.seal,         ' +
                ' b.weight,' +
                ' b.Trucker,                ' +
                ' b.TruckMobile,             ' +
                ' a.customerType ,'        +
                ' a.billType, '            +
                ' a.isLoading ,'           +
                ' cs.fcolor ,'           +
                ' cs.stype as state,               ' +
                ' b.isUse as ctnrIsUse,  ' +
                ' a.isUse as soIsUse     ' +
                ' from mh_truck.truck_so a        ' +
                ' left join mh_truck.truck_ctnr b on b.blid = a.id        ' +
                ' left join mh_form.list_ctnrstate cs on cs.Id = b.Idx_ctnrstate  ' +
                ' where ( b.id = '+t_ctnrId+')';
        sql+=' and b.isUse = 0 limit 1';

        let detail = await think.model('truck_so','mh_truck').query(sql);
        let address = await think.model('truck_address','mh_truck').where({'ctnrId':t_ctnrId}).field('FactoryAddress,FactoryName,contact,Tel,mobile,remarks,orderByIdx').order('orderByIdx asc').select();
        let picture = await think.model('list_file','mh_file').where({"order_no":t_ctnrId,"sType":209}).find();
        if(think.isEmpty(detail))
        {
            return this.fail(1,'暂无数据');
        }else{
            detail[0].address=address;
            detail[0].picture=picture;
            return this.success(detail,'ok');
        }
    }
    /**
    * 获取运费列表
    */
    async getTransFeeListAction(){
        let t_ctnrId = this.get('t_ctnrId'); 
        if(think.isEmpty(t_ctnrId))
        {
            return this.fail(1,'参数异常,无法获取费用信息');
        }
        let sType = this.user.sType;
        if(sType==1)
        {
            //员工
            let bills = await think.model('truck_bill','mh_finance').where({'ctnrid':t_ctnrId}).field('BillUse,receiptDeparment,receipt,paymentType,payment,remarkByReceipt').select();
            if(think.isEmpty(bills))
            {
                return this.fail(1,'暂无数据');
            }else{
                return this.success(bills,'ok');
            }
        }else if(sType==2)
        {
            //客户
            let bills = await think.model('truck_bill','mh_finance').where({'ctnrid':t_ctnrId,'receiptDeparment':'客户'}).field('BillUse,receipt,remarkByReceipt').select();
            if(think.isEmpty(bills))
            {
                return this.fail(1,'暂无数据');
            }else{
                return this.success(bills,'ok');
            }
        }else if(sType==3)
        {
            //司机
            let bills = await think.model('truck_bill','mh_finance').where({'ctnrid':t_ctnrId,'paymentType':'车主'}).field('BillUse,payment,remarkByReceipt,paymentToTrucker').select();
            if(think.isEmpty(bills))
            {
                return this.fail(1,'暂无数据');
            }else{
                return this.success(bills,'ok');
            }
        }else{
            return this.fail(1,'用户身份stype异常,暂无数据');
        }
    }

    /**
    * 根据id获取司机薪水详情
    */
    async getTruckerSalaryAction(){
        let user = this.user;
        let sid = this.post('sid');
        if(think.isEmpty(sid))
        {
            return this.fail(1,'参数异常');
        }
        let sType = user.sType;
        if(sType!=3)
        {
            return this.fail(1,'当前身份暂无可查看的数据');
        }
        let salary = await think.model('trucker_salary','mh_finance').where({'Id':sid}).find();
        if(!think.isEmpty(salary))
        {
            return this.success(salary,'ok');
        }else{
            return this.fail(1,'暂无数据');
        }
    }
    /**
    *根据t_ctnrId获取司机薪水详情
    */
    async getTruckerSalaryByCtnridAction(){
        let user = this.user;
        let sid = this.post('t_ctnrId');
        if(think.isEmpty(sid))
        {
            return this.fail(1,'参数异常');
        }
        let sType = user.sType;
        if(sType!=3)
        {
            return this.fail(1,'当前身份暂无可查看的数据');
        }
        let salary = await think.model('trucker_salary','mh_finance').where({'ctnrId':sid}).find();
        if(!think.isEmpty(salary))
        {
            return this.success(salary,'ok');
        }else{
            return this.fail(1,'暂无数据');
        }
    }

    /**
    *根据获取车辆的位置信息
    */
    async getLocationAction(){
        let sid = this.get('plate_no'); 
        if(think.isEmpty(sid))
        {
            return this.fail(1,'参数异常,无法获取车牌信息');
        }

        let sql = "SELECT A.*,B.longitude,B.latitude,B.Angle,case "+
        "when (IFNULL(B.location_time,'1899-12-31 00:00:00')<DATE_SUB(NOW(),INTERVAL 10 MINUTE)) then '掉线' "+
        "when (IFNULL(B.is_acc_on,0)=0) and (IFNULL(B.speed,0)=0) then '停车' "+
        "when (IFNULL(B.is_acc_on,0)=1) and (IFNULL(B.speed,0)=0) then '未熄火' else '行驶中' end state "+
        "FROM tbldevice A "+
        "LEFT JOIN tbldevice_location B ON A.phone = B.phone "+
        "WHERE A.plate_no = '"+sid+"' ORDER BY B.createtime DESC limit 0,1 ";
        let location = await think.model('tbldevice','mh_gps').query(sql);
        if(think.isEmpty(location))
        {
            return this.fail(1,'暂无数据');
        }else{
            return this.success(location,'ok');
        }
    }

    /**
    * 插入查询位置信息的日志
    */
    async addLogsAction(){
        let bindinfo = this.user;
        let sid = this.post('plate_no'); 
        let user = await think.model('user','mh_user').where({'Id':bindinfo.userid}).field('Id as id,name as username').find();
        let insert = 'insert into log_view (' + 'sName ,' + 'sDate ,' + 'sTruck ,' + 'sType ' + ') values(\'' + user.username+'\',' + 'NOW() ,\'' + sid+'\',' + '1' + ')' ; 
        let row = await think.model('log_view','mh_gps').execute(insert);
        return this.success(row,'ok');
    }

    /**
    *查询出车费
    */
    async getchuchefeiAction(){
        let bindinfo = this.user;
        if(parseInt(bindinfo.sType)!=3)
        {
            return this.fail(1,'只能司机才能查看此页面哦');
        }
        let res = await think.model('wechat_paylist','mh_finance').where({"sName":bindinfo.CName}).order('Id desc').select();
        return this.success(res,'ok');
    }

    /**
    *查询出车费明细
    */
    async getchuchefeidetailAction(){
        let payid = this.get('payid');
        if(parseInt(bindinfo.sType)!=3)
        {
            return this.fail(1,'只能司机才能查看此页面哦');
        }
        let res = await think.model('trucker_salary','mh_finance').where({"paymentId":payid}).find();
        return this.success(res,'ok');
    }

    /**
    * 查询出车费列表
    */
    async getchuchefeilistAction(){
        let querydate = this.get('date');
        let date=querydate.split('-');
        let newdatestart = new Date(parseInt(date[0]),parseInt(date[1])-1,parseInt(date[2])).setHours(0,0,0,0)
        let newdateend = new Date(parseInt(date[0]),parseInt(date[1])-1,parseInt(date[2])).setHours(23,59,59,59);
        newdatestart=global.date(parseInt(newdatestart)/1000,1);
        newdateend=global.date(parseInt(newdateend)/1000,1);
        let bindinfo = this.user;
        if(parseInt(bindinfo.sType)==2)
        {
            //客户
            return this.fail(1,'您无法查看此数据');
        }
        if(parseInt(bindinfo.sType)==3)
        {
            //司机
            let list = await think.model('trucker_salary','mh_finance').where({'dateOfPlan':['between',newdatestart,newdateend],"Trucker":this.user.CName}).select();
            return this.success(list,'ok');
        }
        if(parseInt(bindinfo.sType)==1)
        {
            //员工
            let res = await think.model('trucker_salary','mh_finance').where({'dateOfPlan':['between',newdatestart,newdateend]}).select();
            return this.success(res,'ok');
        }
        
    }
    /**
    * 根据ctnrid查询出车费列表
    */
    async getchuchefeilistbyidAction(){
        let id = this.get("t_ctnrId");
        let list = await think.model('trucker_salary','mh_finance').where({"ctnrId":id}).select();
        return this.success(list,'ok');
    }


	
	/**
	 * 查看订单的相关照片
	 */
	async getOrderPicAction(){
		let sid = this.get('t_ctnrId');
		let list = await think.model('list_file','mh_file').where({'order_no':sid}).select();
		if(!think.isEmpty(list))
		{
			return this.success(list,'ok');
		}else{
			return this.fail(1,'暂无数据');
		}
	}
	
	/**
	 * 上传入库单，柜号等图片的地址信息
	 */
	async uploadPicInfoAction(){
		let user = this.user;
		let sid = this.post('t_ctnrId');
		let stype = this.post('sType');
		let fname = this.post('fname');
		let fpath = this.post('fpath');
		let width = this.post('width');
		let height = this.post('height');
        let url = this.post('url');
		let filedate = this.post('filedate');
		if(think.isEmpty(sid))
		{
		    return this.fail(1,'参数异常');
		}
        var resmarks = '';
        if(stype==2)
        {
            resmarks="柜号";
        }
        if(stype==202)
        {
            resmarks="封条";
        }
        if(stype==204)
        {
            resmarks="签收单";
        }
        if(stype==200)
        {
            resmarks="过磅单";
        }
        if(stype==203)
        {
            resmarks="装货照片";
        }
        if(stype==209)
        {
            resmarks="客户签字";
            let file = await await think.model('list_file','mh_file').where({'order_no':sid,'sType':209}).find();
            if(!think.isEmpty(file))
            {
                await think.model('list_file','mh_file').where({'order_no':sid,'sType':209}).delete();
            }
        }
		var map ={
			"order_no":sid,
			"OrderType":2,
			"file_date":filedate||global.date(parseInt(Date.now() / 1000),1),
			"file_name":fname,
			"file_path":fpath,
			"sType":stype,
			"isDelete":0,
			"isCustomerShow":0,
			"width":width,
			"height":height,
			"url":url,
            "remarks":resmarks
		}
		let row = await think.model('list_file','mh_file').add(map);
		if(row>0)
		{
			return this.success(row,'ok');
		}else{
			return this.fail(1,'图片地址保存失败');
		}
	}
};